import { mapState, mapGetters, mapMutations } from 'vuex'
import alert from '../uni_modules/uview-ui/libs/config/props/alert'

export default {
  data() {
    return {
      lakala: {
        appId: 'wxc3e4d1682da3053c',
        envVersion: 'release', // trial: 体验版, release: 正式版
        path: 'payment-cashier/pages/checkout/index?source=WECHATMINI&counterUrl=',
        fail: () => {
          uni.showToast({ title: '支付失败', icon: 'error', duration: 1500 })
        }
      },
      orderId: '',
      // 支付成功跳转页
      paySuccessRedirectURL: '/cartPack/paymentSuccess/paymentSuccess',
      // 判断是否支付成功接口
      isHadPaymentAPI: '/order-center/car-owner-order/pay-success-page',
	  type:'goods',
    }
  },
  computed: {
    ...mapState('global', ['showInfo']),
  },
  methods: {
    ...mapMutations('global', ['setShowInfo']),
    
    // 跳支付
    toPay(counterUrl, options = {}) {
      // 跳转拉卡拉支付
      const params = { ...this.lakala }
      params.path += encodeURIComponent(counterUrl)
      params.fail = () => {
        this.payFailed('支付失败')
      }
      if (options.paySuccessRedirectURL) {
        this.paySuccessRedirectURL = options.paySuccessRedirectURL
      }
      if (options.isHadPaymentAPI) {
        this.isHadPaymentAPI = options.isHadPaymentAPI
      }
	  if(options.type){
		  this.type = options.type
	  }
	  console.log(this.type)
      uni.navigateToMiniProgram(params)
    },
    
    // 支付成功
    paySuccess() {
      uni.showToast({ title: '支付成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({
          url: this.paySuccessRedirectURL,
          success: (res) => {
            // 发布支付成功事件
            uni.$emit('paymentSuccess',{ orderId: this.orderId })
          }
        })
      }, 1500)
			
			// 埋点
			// this.$uma.trackEvent('order-pay');
			// this.autoReport({
			// 	pageName: '结算页',
			// 	eventCode: 'order-pay',
			// 	businessId: this.orderId
			// })
    },
    
    // 支付失败（或5s内未查到支付信息）
    payFailed () {
      uni.showToast({ title: '未查到支付信息', icon: 'error' })
    },
    
    // 是否已支付
    async isHadPayment() {
      try {	
		if(this.type == 'rescue'){
			const { datas } = await this.$request({
			  url: this.isHadPaymentAPI,
			  data: { id: this.orderId }
			})
			return Promise.resolve(true)
		}else if(this.type == 'guarantee'){
			const { datas } = await this.$request({
				method: 'get',
				url: this.isHadPaymentAPI,
			})
			return Promise.resolve(datas.claimStatus == 4)	
		}else{
			const { datas } = await this.$request({
			  url: this.isHadPaymentAPI,
			  data: { orderId: this.orderId, type: 1 }
			})
			return Promise.resolve(datas.orderState === 4)	
		}

       
      } catch (err) {
        return Promise.resolve(false)
      }
    },
    
    /**
     * 查询支付状态
     * 调用会立即查询一次，在指定次数内查询到支付成功，立即调用成功处理方法；
     * 指定次数内未查到支付成功信息，则每秒查询一次，直至查询次数归零。
     * @param {Number} 查询次数（每秒一次，默认五次）。
     */
    async queryPayStatus(n = 5) {
      let hadPayment
      
      try {
        hadPayment = await this.isHadPayment()
      } catch (err) {
        //
      }
      
      if (hadPayment) {
        // 查到支付成功
        // 定时器是防止立即查到成功后，loading闪烁
        setTimeout(() => {
          uni.hideLoading()
          this.paySuccess()
        }, n === 5 ? 1000 : 0)
      } else if (n > 0) {
        // 5秒内未查到成功，间隔一秒后继续查询
        setTimeout(() => {
          this.queryPayStatus(n - 1)
        }, 1000)
      } else {
        // 超过5秒未查到成功
        uni.hideLoading()
        this.payFailed()
      }
    },
    
    // 处理从支付返回
    handleRuturnFromPayment() {
      // 小程序进入前台的相关信息，
      // 仅在 App.vue 的 onShow 中可以取到该信息
      const { referrerInfo } = this.showInfo
      
      if (referrerInfo && (referrerInfo.appId === this.lakala.appId)) {
        uni.showLoading({ title: '查询支付结果中...', mask: true })
        this.setShowInfo({})
        this.queryPayStatus()
      }
    },
  },
  onShow() {
    this.handleRuturnFromPayment()
  },
}
